import { ExtensionContext, Uri, window, ViewColumn } from "vscode";
import * as path from 'path';
import { twsManager } from "../TwsManager";
class WebviewCommand {
    createWebview(context: ExtensionContext, initData?: any) {
        let panel: any
        panel = window.createWebviewPanel('ThoughtWorks Learning Platform',
            "ThoughtWorks Learning Platform",
            ViewColumn.One, {
                enableScripts: true,
                retainContextWhenHidden: true,
                localResourceRoots: [Uri.file(path.join(context.extensionPath, 'out'))]
            });

        panel.webview.html = this.getWebview(context, initData);

        panel.webview.onDidReceiveMessage((message: any) => {
            panel.webview.postMessage({ type: 'LOGIN_INFO', params: { ...twsManager.getUser() } })
            panel.webview.postMessage(message)
            return;
        },
            null,
            context.subscriptions
        );
        return panel
    }

    getWebview(context: ExtensionContext, routeData: any): any {

        const jsonData = JSON.stringify(routeData)
        return `
                    <!DOCTYPE html>
                    <html lang="en">
                    <head>
                        <meta charset="utf-8">
                        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
                    </head>
                    <body>
                    <script>
                    const vscode = acquireVsCodeApi()
                    </script>
                        <div id="root"></div>
                        <script src="${this.loadFile(context, 'out/aliens.js')}"></script>
                        <script src="${this.loadFile(context, 'out/vendor.js')}"></script>
                        <script>
                            vscode.postMessage(${jsonData})
                        </script>
                    </body>
                    </html>
                `;
    }
    private loadFile(context: ExtensionContext, path: string) {
        return Uri.file(context.asAbsolutePath(path)).with({ scheme: 'vscode-resource' }).toString()
    }
}

export const webviewCommand = new WebviewCommand